<!-- 面包屑 -->
<template>
  <div class="app-breadcrumb" :class="{ 'has-scroll-btn': showScrollBtn }" v-if="device === 'desktop'">
    <div class="d-scroll-view" ref="dScrollViewRef">
      <div class="d-scroll-content" ref="dScrollContentRef">
        <transition-group name="breadcrumb">
          <div class="breadcrumb-item" v-for="(item,index) in levelList" :key="item.path">
            <span v-if="item.meta?.redirect === 'noRedirect' || index == levelList.length - 1 || item.disabled" class="breadcrumb-style no-redirect"><span>{{ item.meta.title }}</span></span>
            <a v-else @click.prevent="handleLink(item)" class="breadcrumb-style breadcrumb-link"><span>{{ item.meta.title }}</span></a>
          </div>
        </transition-group>
      </div>
    </div>
    <div class="scroll-button left" v-show="showScrollBtn" @click="scrollToLeft">
      <el-icon><ArrowLeft /></el-icon>
    </div>
    <div class="scroll-button right" v-show="showScrollBtn" @click="scrollToRight">
      <el-icon><ArrowRight /></el-icon>
    </div>
  </div>
</template>
<script setup lang="ts">
import { compile } from 'path-to-regexp'
import { RouteLocationMatched, RouteRecord, RouteRecordRaw, useRoute, useRouter } from 'vue-router';
import { ArrowLeft, ArrowRight } from '@element-plus/icons-vue';
import { useAppStore } from '@/store/app';
const router = useRouter()
const route = useRoute()
const appStore = useAppStore()
const device = computed(() => appStore.device)

const levelList = ref<Array<KeyValue>>([])

// 是否是首页
const isHome = (route: KeyValue) => {
  const name: string = route && route.name as string
  if (!name) {
    return false
  }
  return name.trim().toLocaleLowerCase() === 'Home'.toLocaleLowerCase()
}
// 获取面包屑导航
const getBreadcrumb = () => {
  // 仅仅显示路由的meta.title
  let matched: Array<any> = []
  route.matched.forEach((item: KeyValue, key: number) => {
    // 默认全都不可以点
    item.disabled = true
    // 如果子路由只有一个 查看是否是当前页面 或 是否是空path（相当于本身）
    const showingChildren = item.children?.filter((item: RouteRecord) => item.meta?.hidden ? false : true)
    if (showingChildren && showingChildren.length === 1) {
      let first = showingChildren[0]
      if (first.children?.length > 0) {
        if (item?.meta?.title) {
          matched.push(item)
          return
        } else {
          if (item.children?.find((item: KeyValue) => item?.path === '')) {
            matched.push(item)
            return
          }
        }
      } else {
        // 是否是当前页面
        if (first.name !== route.name && first?.meta?.title) {
          if (first.path === '') {
            matched.splice(key, 0, { ...first, disabled: false, path: item.path })
            return
          }
        }
      }
    } else {
      if (item?.meta?.title) {
        matched.push(item)
        return
      } else {
        if (item.children?.find((item: KeyValue) => item?.path === '')) {
          matched.push(item)
          return
        }
      }
    }

  })
  const first = matched[0]

  if (!isHome(first)) {
    matched = [{ path: '/home', meta: { title: '首页' }}].concat(matched, [])
  }

  levelList.value = matched.filter(item => item.meta && item.meta.title && item.meta.breadcrumb !== false)


  // 更新是否显示滚动
  nextTick(() => {
    checkScrollWidth()
  })
}
onMounted(() => {
  getBreadcrumb()
})

watch(route, route => {
  // 如果转到重定向页面，不更新面包屑
  if (route.path.startsWith('/redirect/')) {
    return
  }
  getBreadcrumb()
})
// 解析路径
const pathCompile = (path: string) => {
  const { params } = route
  var toPath = compile(path)
  return toPath(params)
}
// 点击面包屑
const handleLink = (item) => {
  const { redirect, path } = item
  if (redirect) {
    router.push(redirect)
    return
  }
  router.push(pathCompile(path))
}



/** 滚动相关 */
const dScrollViewRef = ref<null | HTMLDivElement>()
const dScrollContentRef = ref<null | HTMLDivElement>()
const showScrollBtn = ref(false)
/**
 * 更新宽度，检测是否显示滚动按钮
 */
const checkScrollWidth = () => {
  nextTick(() => {
    setTimeout(() => {
      if (dScrollViewRef.value && dScrollContentRef.value) {
        if (dScrollViewRef.value?.getBoundingClientRect().width < (dScrollContentRef.value?.getBoundingClientRect().width + 50)) {
          showScrollBtn.value = true
        } else {
          showScrollBtn.value = false
        }
      } else {
        showScrollBtn.value = false
      }
    }, 100);
  })
}
/**
 * 向右滚
 */
const scrollToRight = () => {
  if (dScrollViewRef.value) {
    dScrollViewRef.value.scrollTo({ left: dScrollViewRef.value.scrollLeft + dScrollViewRef.value?.getBoundingClientRect().width, behavior: 'smooth' })
  }
}
/**
 * 向左滚
 */
const scrollToLeft = () => {
  if (dScrollViewRef.value) {
    dScrollViewRef.value.scrollTo({ left: (dScrollViewRef.value.scrollLeft > 0) ? (dScrollViewRef.value.scrollLeft - dScrollViewRef.value?.getBoundingClientRect().width) : 0, behavior: 'smooth' })
  }
}

</script>
<style scoped lang="scss">
.app-breadcrumb {
  font-size: 14px;
  line-height: 50px;
  margin-left: 8px;
  flex: 1;
  position: relative;
  overflow: auto;
  .breadcrumb-item {
    width: auto;
    word-break: nowrap;
    white-space: nowrap;
    display: inline-block;
    > .breadcrumb-style {
      padding: 5px;
      background-color: #e7e7e7;
      transition: background-color .3s, color .3s;
      padding: 5px 14px;
      border-radius: 4px;
      clip-path: polygon(0 0,calc(100% - 8px) 0,100% 50%,calc(100% - 8px) 100%,0 100%,8px 50%);
      &:hover {
        color: #0062ff;
        background-color: #d6d6d6;
      }
    }
    .no-redirect {
      color: #97a8be;
      cursor: no-drop;
      &:hover {
        color: #97a8be;
        background-color: #e7e7e7;
      }
    }
    &:first-of-type {
      > .breadcrumb-style {
        clip-path: polygon(0 0,calc(100% - 8px) 0,100% 50%,calc(100% - 8px) 100%,0 100%);
        > span {
          display: inline-block;
          transform: translateX(-2px);
        }
      }
    }
    &:last-of-type {
      > .breadcrumb-style {
        clip-path: polygon(0 0,100% 0,100% 50%,100% 100%,0 100%,8px 50%);
        background-color: #cccdce !important;
        color: #000;
        > span {
          display: inline-block;
          transform: translateX(2px);
        }
      }
    }
  }

}


// 滚动相关
.has-scroll-btn {
  padding: 0 25px;
}
.d-scroll-view {
  width: 100%;
  overflow: hidden;
  white-space: nowrap;
  position: relative;
  box-sizing: border-box;
  .d-scroll-content {
    width: auto;
    display: inline-flex;
    width: auto;
    flex-wrap: nowrap;
    white-space: nowrap;
    &::-webkit-scrollbar {
      display: none;
    }
  }
}
.scroll-button {
  position: absolute;
  top: 50%;
  transform: translateY(-50%);
  bottom: 0;
  width: 20px;
  height: 25px;
  color: #000;
  text-align: center;
  cursor: pointer;
  transition: all .3s;
  font-size: 18px;
  border-radius: 4px;
  background-color: #fff;
  &:hover {
    background-color: #e0e0e0;
  }
}
.scroll-button.left {
  left: 0;
}
.scroll-button.right {
  right: 0;
}
.scroll-button i {
  position: absolute;
  top: 50%; 
  left: 50%; 
  transform: translate(-50%, -50%); 
}

</style>